package com.example.springboot.controller;

import com.example.springboot.common.Result;
import com.example.springboot.controller.request.BookPageRequest;
import com.example.springboot.entity.Book;
import com.example.springboot.service.IBookService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
@CrossOrigin
@RestController
@RequestMapping("/book")
public class BookController {
    @Resource
    IBookService bookService;


    @PostMapping("/addBook") //定义addBook接口添加书籍   //http://localhost:8060/book/addBook
    public Result save(@RequestBody Book book){
        bookService.save(book);
        return Result.success();
    }

    @PutMapping("/{bookId}") // 借书
    public Result borrowBook(@PathVariable Long bookId) {
        if (bookService.canBorrowBook(bookId)) {
            boolean success = bookService.borrowBook(bookId); //
            if (success) {
                return Result.success("借书成功");
            } else {
                return Result.error("借书失败");
            }
        } else {
            return Result.error("借书失败，库存不足");
        }
    }

    @PutMapping("/update/{bookId}")//更新书籍信息
    public Result updateBook(@PathVariable Long bookId, @RequestBody Book book) {
        boolean success = bookService.updateBook(bookId, book);
        if (success) {
            return Result.success();
        } else {
            return Result.error();
        }
    }

    @GetMapping("/list")//获取book表数据
    public Result list(){
        List<Book> book = bookService.list();
        return Result.success(book);
    }

    @GetMapping("/page") //分页查询book表数据
    public Result page(BookPageRequest bookPageRequest){
        return Result.success(bookService.page(bookPageRequest));
    }


    @PutMapping("/incrementTotalCopies")//还书
    public Result incrementTotalCopiesByTitle(@RequestParam String title) {
        boolean success = bookService.incrementTotalCopiesByTitle(title);
        if (success) {
            return Result.success();
        } else {
            return Result.error();
        }
    }


}
